package com.vehiclesecure.controller;

import com.vehiclesecure.model.User;
import com.vehiclesecure.model.VehicleData;
import com.vehiclesecure.service.UserService;
import com.vehiclesecure.service.VehicleDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 车辆数据控制器，处理与车辆数据相关的HTTP请求
 */
@RestController
@RequestMapping("/api/vehicle-data")
public class VehicleDataController {
    
    private final VehicleDataService vehicleDataService;
    private final UserService userService;
    
    @Autowired
    public VehicleDataController(VehicleDataService vehicleDataService, UserService userService) {
        this.vehicleDataService = vehicleDataService;
        this.userService = userService;
    }
    
    /**
     * 获取当前登录用户
     * @return 当前登录用户对象
     */
    private User getCurrentUser() {
        String email = SecurityContextHolder.getContext().getAuthentication().getName();
        return (User) userService.loadUserByUsername(email);
    }
    
    /**
     * 提交新的车辆数据
     * @param vehicleData 车辆数据对象
     * @return 保存后的车辆数据
     */
    @PostMapping
    public ResponseEntity<VehicleData> submitVehicleData(@RequestBody VehicleData vehicleData) {
        VehicleData savedData = vehicleDataService.saveVehicleData(vehicleData);
        return ResponseEntity.ok(savedData);
    }
    
    /**
     * 获取指定车辆的所有数据
     * @param vehicleId 车辆唯一标识符
     * @return 车辆数据列表
     */
    @GetMapping("/vehicle/{vehicleId}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN', 'SERVICE_PROVIDER')")
    public ResponseEntity<List<VehicleData>> getVehicleDataByVehicleId(@PathVariable String vehicleId) {
        User currentUser = getCurrentUser();
        
        // 服务商可以访问所有车辆的维修数据
        if (currentUser.getRole() != User.Role.SERVICE_PROVIDER && 
            !vehicleDataService.hasAccessToVehicle(currentUser, vehicleId)) {
            return ResponseEntity.status(403).build(); // 权限不足
        }
        
        List<VehicleData> vehicleDataList = vehicleDataService.getVehicleDataByVehicleId(vehicleId);
        return ResponseEntity.ok(vehicleDataList);
    }
    
    /**
     * 获取指定车辆在时间范围内的数据
     * @param vehicleId 车辆唯一标识符
     * @param start 开始时间
     * @param end 结束时间
     * @return 车辆数据列表
     */
    @GetMapping("/vehicle/{vehicleId}/time-range")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN', 'SERVICE_PROVIDER')")
    public ResponseEntity<List<VehicleData>> getVehicleDataByTimeRange(
            @PathVariable String vehicleId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
        
        User currentUser = getCurrentUser();
        
        // 服务商可以访问所有车辆的维修数据
        if (currentUser.getRole() != User.Role.SERVICE_PROVIDER && 
            !vehicleDataService.hasAccessToVehicle(currentUser, vehicleId)) {
            return ResponseEntity.status(403).build(); // 权限不足
        }
        
        List<VehicleData> vehicleDataList = vehicleDataService.getVehicleDataByVehicleIdAndTimeRange(vehicleId, start, end);
        return ResponseEntity.ok(vehicleDataList);
    }
    
    /**
     * 获取所有紧急情况数据
     * @return 紧急情况数据列表
     */
    @GetMapping("/emergency")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<List<VehicleData>> getEmergencyVehicleData() {
        List<VehicleData> emergencyData = vehicleDataService.getEmergencyVehicleData();
        return ResponseEntity.ok(emergencyData);
    }
    
    /**
     * 根据ID获取车辆数据
     * @param id 数据ID
     * @return 车辆数据对象
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasAnyRole('USER', 'ADMIN', 'SERVICE_PROVIDER')")
    public ResponseEntity<VehicleData> getVehicleDataById(@PathVariable String id) {
        User currentUser = getCurrentUser();
        
        java.util.Optional<VehicleData> vehicleDataOptional = vehicleDataService.getVehicleDataById(id);
        
        if (vehicleDataOptional.isPresent()) {
            VehicleData vehicleData = vehicleDataOptional.get();
            
            // 服务商可以访问所有车辆的维修数据
            if (currentUser.getRole() != User.Role.SERVICE_PROVIDER && 
                !vehicleDataService.hasAccessToVehicle(currentUser, vehicleData.getVehicleId())) {
                return ResponseEntity.status(403).build(); // 权限不足
            }
            
            return ResponseEntity.ok(vehicleData);
        }
        
        return ResponseEntity.notFound().build();
    }
    
    /**
     * 获取当前用户有权访问的所有车辆数据
     * @return 用户有权访问的车辆数据列表
     */
    @GetMapping
    @PreAuthorize("hasAnyRole('USER', 'ADMIN', 'SERVICE_PROVIDER')")
    public ResponseEntity<List<VehicleData>> getUserAccessibleVehicleData() {
        User currentUser = getCurrentUser();
        
        // 服务商可以访问所有车辆的维修数据
        if (currentUser.getRole() == User.Role.SERVICE_PROVIDER) {
            List<VehicleData> allVehicleData = vehicleDataService.getAllVehicleData();
            return ResponseEntity.ok(allVehicleData);
        }
        
        List<VehicleData> vehicleDataList = vehicleDataService.getUserAccessibleVehicleData(currentUser);
        return ResponseEntity.ok(vehicleDataList);
    }
    
    /**
     * 获取交通流量统计数据
     * @return 交通流量统计信息
     */
    @GetMapping("/traffic-stats")
    public ResponseEntity<VehicleDataService.TrafficStats> getTrafficStats() {
        VehicleDataService.TrafficStats stats = vehicleDataService.getTrafficStats();
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 获取停车数据分析
     * @return 停车数据分析
     */
    @GetMapping("/parking-stats")
    public ResponseEntity<VehicleDataService.ParkingStats> getParkingStats() {
        VehicleDataService.ParkingStats stats = vehicleDataService.getParkingStats();
        return ResponseEntity.ok(stats);
    }
}